package org.abc.fund.service.trade;

import org.abc.fund.entity.trade.Account;
import org.abc.fund.repository.trade.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class AccountService {

  private final AccountRepository accountRepository;

  public AccountService(AccountRepository accountRepository) {
    this.accountRepository = accountRepository;
  }

  /**
   * 创建一个新账户.
   *
   * @param account 要创建的账户对象.
   * @return 保存后的账户实体.
   * @throws IllegalStateException 如果该用户的账户已存在.
   */
  @Transactional
  public Account createAccount(Account account) {
    if (accountRepository.existsById(account.getUserId())) {
      throw new IllegalStateException(
          "Account for user ID " + account.getUserId() + " already exists.");
    }
    return accountRepository.save(account);
  }

  /**
   * 根据用户ID查询账户.
   *
   * @param userId 用户的ID.
   * @return 一个包含账户的Optional，如果找到的话.
   */
  @Transactional(readOnly = true)
  public Optional<Account> getAccountByUserId(Long userId) {
    return accountRepository.findById(userId);
  }
}
